var flowTable;
var num=0;
$(function () {

    $.ajax({
        type: "post",
        data:{"treeKey":"flowmodel"},
        dataType: "json",
        url: base_url+"/product/getTreeNode",
        success: function(defaultData) {
            // if(defaultData.length<=0){
            //     defaultData[0].state = {
            //         checked:true,
            //         expanded:true,
            //         selected:true
            //     }
            // }
            if(defaultData.length>0)
            {
                $('#treeId_find').val(defaultData[0].id);
            }

            initFlowTable();
            $('#treeview5').treeview({
                color: "#428bca",
//  				expandIcon: 'glyphicon glyphicon-chevron-right',
//  				collapseIcon: 'glyphicon glyphicon-chevron-down',
//  				nodeIcon: 'glyphicon glyphicon-bookmark',
                emptyIcon: '',
                // 没有子节点的节点图标
                levels: 1,
                data: defaultData,
                onNodeSelected: function (event, data) {
                    $('#treeId_find').val(data.id);
                    flowTable.fnDraw();
                }
            });
        }
    });

    function getparent(nodeId,parentList){
        var arr = $('#treeview5').treeview("getParent", nodeId);
        var a=[arr.text,arr.id];
        if(arr.nodeId!=undefined){
            parentList.push(a);
            return getparent(arr.nodeId,parentList);
        }else{
            return parentList;
        }
    }

    $("#treeAdd").click(function () {
        var parentList = new Array();
        var arr = [];
        var arr = $('#treeview5').treeview('getSelected');
        var obj = {};
        obj.start=0;
        obj.length=10;
        obj.processCHName=$('#processCHName').val();
        obj.treeId=$("#treeId_find").val();
        if(arr.length<=0)
        {
            obj.processCHName="";
            obj.treeId=0;
        }

        //判断该节点是否有流程 有流程线就不能再创建下一级节点
        $.ajax({
            type:"post",
            dataType:"json",
            url: base_url + "/flow/pageList",
            data: obj,
            success:function (data) {
                if(data.data.length>0)
                {
                    layer.open({
                        title: '系统提示',
                        content: ("不能在有流程的节点下增加子节点！"),
                        icon: '0'
                    });
                    return;
                }

                // show
                $('#addModal1').modal({
                    backdrop: false,
                    keyboard: false
                }).modal('show');
            }
        })

        if (arr.length > 0) {
            getparent(arr[0].nodeId, parentList);
            var menu = "";
            var menuId = "";
            for (var i = parentList.length - 1; i >= 0; i--) {
                menu += parentList[i][0] + ">";
                menuId += parentList[i][1] + ",";
            }
            if (arr[0].id == "treeview5") {
                $("#addModal1 .form input[name='parentId']").val("0");
                $("#addModal1 .form input[name='menu']").val("");
            } else {

                $("#addModal1 .form input[name='parentId']").val(arr[0].id);


                $("#addModal1 .form input[name='menu']").val(menu + arr[0].text);
            }
            $("#addModal1 .form input[name='menuId']").val("");
        } else {
            $("#addModal1 .form input[name='parentId']").val("0");
        }
    });

    var addModalValidate = $("#addModal1 .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules : {
            text : {
                required : true
            }
        },
        messages : {
            text : {
                required :"请输入目录名称！"
            }
        },
        highlight : function(element) {
            $(element).closest('.col-sm-4').addClass('has-error');
        },
        success : function(label) {
            label.closest('.col-sm-4').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
          var info=  $("#addModal1 .form").serialize();
            $.post(base_url + "/product/save",  $("#addModal1 .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#addModal1').modal('hide');
                    layer.msg('新增成功', {
                        icon: 1,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function(){
                        $.ajax({
                            type: "post",
                            data:{"treeKey":"flowmodel"},
                            dataType: "json",
                            url: base_url+"/product/getTreeNode",
                            success: function(defaultData) {
                                // for(var i=0;i<defaultData.length;i++){
                                //     var info =$('#treeview5').treeview('getSelected');
                                //     console.log(info);
                                //     if(defaultData[i].id== $('#treeview5').treeview('getSelected')[0].id){
                                //         defaultData[i].state = {
                                //             checked:true,
                                //             expanded:true,
                                //             selected:true
                                //         }
                                //     }
                                // }

                                $('#treeview5').treeview({
                                    color: "#428bca",
                                    emptyIcon: '',
                                    levels: 1,
                                    data: defaultData,
                                    onNodeSelected: function (event, data) {
                                        $('#treeId_find').val(data.id);
                                        flowTable.fnDraw();
                                    }
                                })
                            }
                        });
                    });
                } else {
                    layer.msg(data.msg || "新增失败", {
                        icon: 2,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }

            });
        }
    });

    var updateModalValidate = $("#updateModal1 .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules : {
            text : {
                required : true
            }
        },
        messages : {
            text : {
                required :"请输入目录名称！"
            }
        },
        highlight : function(element) {
            $(element).closest('.col-sm-4').addClass('has-error');
        },
        success : function(label) {
            label.closest('.col-sm-4').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $.post(base_url + "/product/save",  $("#updateModal1 .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#updateModal1').modal('hide');
                    layer.msg('更新成功', {
                        icon: 1,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function(){
                        $.ajax({
                            type: "post",
                            data:{"treeKey":"flowmodel"},
                            dataType: "json",
                            url: base_url+"/product/getTreeNode",
                            success: function(defaultData) {
                                for(var i=0;i<defaultData.length;i++){
                                    if(defaultData[i].id== $('#treeview5').treeview('getSelected')[0].id){
                                        defaultData[i].state = {
                                            checked:true,
                                            expanded:true,
                                            selected:true
                                        }
                                    }
                                }
                                $('#treeview5').treeview({
                                    color: "#428bca",
                                    emptyIcon: '',
                                    levels:1,
                                    data: defaultData,
                                    onNodeSelected: function (event, data) {
                                        $('#treeId_find').val(data.id);
                                        flowTable.fnDraw();
                                    }
                                });
                            }
                        });
                    });
                } else {
                    layer.msg(data.msg || "更新失败", {
                        icon: 2,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }
            });
        }
    });

    $("#treeUpdate").click(function() {
        var parentList = new Array();
        var arr = $('#treeview5').treeview('getSelected');
        if (arr.length ==0){
            layer.open({
                title: '系统提示',
                content: ("请选择目录"),
                icon: '2'
            });
            return;
        }
        getparent(arr[0].nodeId, parentList);
        var menu = "";
        var menuId = "";
        for (var i = parentList.length - 1; i >= 0; i--) {
            menu += parentList[i][0] + ">";
            menuId += parentList[i][1] + ",";
        }
        // base data
        $("#updateModal1 .form input[name='id']").val(arr[0].id);
        $("#updateModal1 .form input[name='text']").val(arr[0].text);
        $("#updateModal1 .form input[name='parentId']").val("0");
        $("#updateModal1 .form input[name='menu']").val(menu+arr[0].text);
        $("#updateModal1 .form input[name='menuId']").val(menuId+arr[0].id);
        /*var iconPath = "";
        if("undefined" != menuId+arr[0].iconPath){
            iconPath =  menuId+arr[0].iconPath;
        }
        $("#updateModal .form select[name='iconPath']").find("option:selected").val();*/

        // show
        $('#updateModal1').modal({
            backdrop: false,
            keyboard: false
        }).modal('show');
    });

    $("#treeDel").click(function() {
        if($('#treeview5').treeview('getSelected').length>0){
            layer.confirm('确认删除?', {icon: 3, title:'系统提示'}, function(index){
                layer.close(index);
                var arr = $('#treeview5').treeview('getSelected');
                var data = {
                    "id": arr[0].id
                };
                $.ajax({
                    type: "post",
                    data: data,
                    dataType: "json",
                    url: base_url+"/product/deleteTreeNode",
                    success: function(data) {
                        if (data.code == "200") {
                            layer.msg('操作成功', {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            }, function(){
                                window.location.href = base_url+ "/flow";
                            });
                        } else {
                            layer.msg(data.msg || "操作失败", {
                                icon: 2,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            });
                        }
                    }
                });
            });
        }else{
            layer.msg("请选择将要删除节点", {
                icon: 2,
                time: 2000 //2秒关闭（如果不配置，默认是3秒）
            });
        }
    });

    $('#searchBtn').on('click', function () {
        flowTable.fnDraw();
    });

    //表格渲染代码
    function initFlowTable(){
        flowTable = $("#flowTable").dataTable({
            "deferRender": true,
            "processing": true,
            "serverSide": true,
            "autoWidth":true,//自动列宽
            "bLengthChange":true,//每页多少条框体
            "dom": '<t><lip>',
            "aaSorting": [
                [1, "asc"]
            ],
            "ajax": {
                url: base_url + "/flow/pageList",
                type: "post",
                data: function (d) {
                    var obj = {};
                    obj.start=d.start;
                    obj.length=d.length;
                    obj.processCHName=$('#processCHName').val();
                    obj.treeId=$("#treeId_find").val();
                    num=num+1;
                    console.log("num",num);
                    console.log("treeid",obj.treeId);
                    return obj;
                },
            },
            "searching": false,
            "ordering": false,
            "scrollX": false, // X轴滚动条，取消自适应
            // "scrollY":true,
            // "bSort":false,//避免ajax的二次调用
            "fnDrawCallback": function () {//序号自增回调函数
                this.api().column(0).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
            },
            "columns": [{
                "data": null
            }, {
                "data": 'processCHName',
                "visible": true,
            }, {
                "data": 'processDescribe',
                "visible": true
            }, {
                "data": 'createTime',
                "visible": true,
                "render": function (data, type, row) {
                    return data ? moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss") : "";
                }
            }, {
                "data": 'updateTime',
                "visible": true,
                "render": function (data, type, row) {
                    return data ? moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss") : "";
                }
            }, {
                "data": '操作',
                "width":"200px",
                "render": function (data, type, row) {
                    tableData['key' + row.id] = row;
                    // console.log(num,row.treeId);
                    return function () {
                        return getbutton(row);
                    };
                }
            }
            ],
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "每页 _MENU_ 条记录。",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
                "sInfoEmpty": "无记录",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        });
    }

    //和initFlowTable区别在于将flowTable用函数包了一下，避免了每次按F5刷新都调用两次ajax，其中第一次是空的，没有用
    // flowTable = $("#flowTable").dataTable({
    //     "deferRender": true,
    //     "processing": true,
    //     "serverSide": true,
    //     "autoWidth":true,//自动列宽
    //     "aaSorting": [
    //         [1, "asc"]
    //     ],
    //     "ajax": {
    //         url: base_url + "/flow/pageList",
    //         type: "post",
    //         data: function (d) {
    //             var obj = {};
    //             obj.start=d.start;
    //             obj.length=d.length;
    //             obj.processCHName=$('#processCHName').val();
    //             obj.treeId=$("#treeId_find").val();
    //             num=num+1;
    //             console.log("num",num);
    //             console.log("treeid",obj.treeId);
    //             return obj;
    //         },
    //     },
    //     "searching": false,
    //     "ordering": false,
    //      "scrollX": false, // X轴滚动条，取消自适应
    //     // "scrollY":true,
    //     // "bSort":false,//避免ajax的二次调用
    //     "fnDrawCallback": function () {//序号自增回调函数
    //         this.api().column(0).nodes().each(function (cell, i) {
    //             cell.innerHTML = i + 1;
    //         });
    //     },
    //     "columns": [{
    //         "data": null
    //     }, {
    //         "data": 'processCHName',
    //         "visible": true,
    //     }, {
    //         "data": 'processDescribe',
    //         "visible": true
    //     }, {
    //             "data": 'createTime',
    //             "visible": true,
    //             "render": function (data, type, row) {
    //                 return data ? moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss") : "";
    //             }
    //         }, {
    //             "data": 'updateTime',
    //             "visible": true,
    //             "render": function (data, type, row) {
    //                 return data ? moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss") : "";
    //             }
    //         }, {
    //             "data": '操作',
    //             "render": function (data, type, row) {
    //                 tableData['key' + row.id] = row;
    //                // console.log(num,row.treeId);
    //                 return function () {
    //                     return getbutton(row);
    //                 };
    //             }
    //         }
    //     ],
    //     "language": {
    //         "sProcessing": "处理中...",
    //         "sLengthMenu": "每页 _MENU_ 条记录",
    //         "sZeroRecords": "没有匹配结果",
    //         "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
    //         "sInfoEmpty": "无记录",
    //         "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
    //         "sInfoPostFix": "",
    //         "sSearch": "搜索:",
    //         "sUrl": "",
    //         "sEmptyTable": "表中数据为空",
    //         "sLoadingRecords": "载入中...",
    //         "sInfoThousands": ",",
    //         "oPaginate": {
    //             "sFirst": "首页",
    //             "sPrevious": "上页",
    //             "sNext": "下页",
    //             "sLast": "末页"
    //         },
    //         "oAria": {
    //             "sSortAscending": ": 以升序排列此列",
    //             "sSortDescending": ": 以降序排列此列"
    //         }
    //     }
    // });

    var tableData = {};

    $("#flowAdd").click(function() {
        var flag= $('#treeview5').find("li").length;
        var arr = $('#treeview5').treeview('getSelected');
        if(flag==0) {
            layer.alert('请先创建流程分类', {icon: 0});
            return;
        }
        if (arr.length == 0) {
            layer.alert('请先选择流程分类', {icon: 0});//icon:2 红色的×； 0是！
            return;
        }
       else if(arr.length>0&&arr[0].hasOwnProperty("nodes")) //判断该节点是否子节点，true，不能添加流程线，false 可以
        {
          if(arr[0].nodes.length>0)
          {
            layer.open({
                title: '系统提示',
                content: ("不能在有子节点的情况下继续添加生产线，请选择创建新节点进行添加生产线！"),
                icon: '0'
            });
            return;
         }
        }
        sessionStorage["treeId"]=arr[0].id;
       // sessionStorage["treeId"]=$("#treeId_find").val(); //xyz 修改 by 20191010
        window.open(base_url+"/designer_zh_CN.html","_self");
    });

    $("#shiroCeshi").click(function () {
        layer.alert('shiroCeshi功能', {icon: 0});
    });

	    /**
     * 图片按宽高比例进行自动缩放
     * @param ImgObj
     *     缩放图片源对象
     * @param maxWidth
     *     允许缩放的最大宽度
     * @param maxHeight
     *     允许缩放的最大高度
     * @usage
     *     调用：<img src="图片" onload="javascript:DrawImage(this,100,100)">
     */
    function DrawImage(ImgObj, maxWidth, maxHeight){
        var image = new Image();
        //原图片原始地址（用于获取原图片的真实宽高，当<img>标签指定了宽、高时不受影响）
        image.src = ImgObj.src;
        // 用于设定图片的宽度和高度
        var tempWidth;
        var tempHeight;

        if(image.width > 0 && image.height > 0){
            //原图片宽高比例 大于 指定的宽高比例，这就说明了原图片的宽度必然 > 高度
            if (image.width/image.height >= maxWidth/maxHeight) {
                if (image.width > maxWidth) {
                    tempWidth = maxWidth;
                    // 按原图片的比例进行缩放
                    tempHeight = (image.height * maxWidth) / image.width;
                } else {
                    // 按原图片的大小进行缩放
                    tempWidth = image.width;
                    tempHeight = image.height;
                }
            } else {// 原图片的高度必然 > 宽度
                if (image.height > maxHeight) {
                    tempHeight = maxHeight;
                    // 按原图片的比例进行缩放
                    tempWidth = (image.width * maxHeight) / image.height;
                } else {
                    // 按原图片的大小进行缩放
                    tempWidth = image.width;
                    tempHeight = image.height;
                }
            }
            // 设置页面图片的宽和高
            ImgObj.height = tempHeight;
            ImgObj.width = tempWidth;
            // 提示图片的原来大小
            ImgObj.alt = image.width + "×" + image.height;
        }
    }
	
    $("#flowTable").on('click', '.preview',function() {
        var id = $(this).parent('p').attr("id");
        var url=base_url+"/flow/preview/"+id;     
        $("#previewImage").attr("src",url);
        $('#viewModal').modal('show');
    });

    $("#flowTable").on('click', '.update',function() {
        var id = $(this).parent('p').attr("id");
        window.open(base_url+"/designerUpdate_zh_CN.html?id="+id,"_self");

    });

    function getTreeNode() {
        $.ajax({
            type: "post",
            data: {"treeKey": "flowmodel"},
            dataType: "json",
            url: base_url+"/product/getTreeNode",
            success: function (defaultData) {
                // defaultData[0].state = {
                //     checked: true,
                //     expanded: true,
                //     selected: true
                // }
                 $('#id').val(defaultData[0].id);//没有找到在哪里用到
                $('#treeview5').treeview({
                    color: "#428bca",
                    levels: 1,//默认是2
                    data: defaultData,
                    state:{
                        checked: true,
                        expanded: true,
                        selected: true
                    },
                    onNodeSelected: function (event, data) {
                        $("#treeId_find").val(data.id);
                       // $("#processCHName").val(data.text);
                        flowTable.fnDraw();
                    }
                });
            }
        });
    }

    //查看所有流程
    $("#lookAllFlow").click(function () {
        $("#processCHName").val("");
        $("#treeId_find").val("");
        flowTable.fnDraw();
    });
});

function del(obj) {
    layer.confirm('确认删除?', {icon: 3, title: '系统提示'}, function (index) {
        layer.close(index);
        var id = $(obj).parent('p').attr("id");
        var data = {
            "id": id
        };
        $.ajax({
            type: "post",
            data: data,
            dataType: "json",
            url: base_url + "/flow/deleteFlow",
            success: function (data) {
                if (data.code == 200) {
                    layer.msg('成功', {
                        icon: 1,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function(layero, index){
                        flowTable.fnDraw();
                    });
                } else {
                    layer.msg(data.msg || "操作失败", {
                        icon: 2,
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    });
                }
            }
        });

    });


}

